<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>手机端MQTT控制</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 10px;
        }

        .container {
            max-width: 400px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            text-align: center;
        }

        .header h1 {
            font-size: 1.5rem;
            margin-bottom: 5px;
        }

        .status {
            font-size: 0.9rem;
            opacity: 0.9;
        }

        .section {
            padding: 20px;
            border-bottom: 1px solid #eee;
        }

        .section:last-child {
            border-bottom: none;
        }

        .section h3 {
            color: #333;
            margin-bottom: 15px;
            font-size: 1.1rem;
        }

        .input-group {
            margin-bottom: 15px;
        }

        .input-group label {
            display: block;
            margin-bottom: 5px;
            color: #666;
            font-size: 0.9rem;
        }

        .input-group input, .input-group select {
            width: 100%;
            padding: 12px;
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            font-size: 1rem;
            transition: border-color 0.3s;
        }

        .input-group input:focus, .input-group select:focus {
            outline: none;
            border-color: #667eea;
        }

        .btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 12px 20px;
            border-radius: 10px;
            font-size: 1rem;
            cursor: pointer;
            transition: transform 0.2s, box-shadow 0.2s;
            margin: 5px;
            min-width: 80px;
        }

        .btn:active {
            transform: scale(0.95);
        }

        .btn.secondary {
            background: #6c757d;
        }

        .btn.danger {
            background: #dc3545;
        }

        .btn.success {
            background: #28a745;
        }

        .btn-group {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 10px;
        }

        .preset-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
            margin-top: 10px;
        }

        .preset-btn {
            background: #f8f9fa;
            color: #333;
            border: 2px solid #e0e0e0;
            padding: 15px 10px;
            border-radius: 10px;
            font-size: 0.9rem;
            cursor: pointer;
            transition: all 0.3s;
            text-align: center;
        }

        .preset-btn:active {
            background: #e9ecef;
            transform: scale(0.98);
        }

        .log {
            height: 150px;
            overflow-y: auto;
            border: 1px solid #e0e0e0;
            border-radius: 10px;
            padding: 10px;
            background: #f8f9fa;
            font-size: 0.8rem;
            line-height: 1.4;
        }

        .log div {
            margin-bottom: 5px;
            padding: 3px 0;
            border-bottom: 1px solid #eee;
        }

        .subscription-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: #f8f9fa;
            padding: 10px;
            margin: 5px 0;
            border-radius: 8px;
            border: 1px solid #e0e0e0;
        }

        .subscription-item button {
            background: #dc3545;
            color: white;
            border: none;
            padding: 5px 10px;
            border-radius: 5px;
            font-size: 0.8rem;
        }

        .connection-status {
            display: inline-block;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            margin-right: 8px;
        }

        .status.connected {
            background: #28a745;
        }

        .status.disconnected {
            background: #dc3545;
        }


    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>MQTT控制端</h1>
            <div class="status" id="status">
                <span class="connection-status disconnected"></span>
                未连接
            </div>
        </div>

        <!-- 连接控制 -->
        <div class="section">
            <h3>连接控制</h3>
            <div class="btn-group">
                <button class="btn success" onclick="connectMQTT()">连接</button>
                <button class="btn danger" onclick="disconnectMQTT()">断开</button>
            </div>
        </div>

        <!-- 主题设置 -->
        <div class="section">
            <h3>目标主题设置</h3>
            <div class="input-group">
                <label>发送主题:</label>
                <input type="text" id="targetTopic" placeholder="display/control" value="">
            </div>
            <div class="input-group">
                <label>设备ID (可选):</label>
                <input type="text" id="deviceId" placeholder="设备ID，留空使用默认主题">
            </div>
            <button class="btn" onclick="updateTargetTopic()">更新主题</button>
        </div>

        <!-- 订阅管理 -->
        <div class="section">
            <h3>订阅主题</h3>
            <div class="input-group">
                <input type="text" id="subscribeTopic" placeholder="输入要订阅的主题" value="display/status">
            </div>
            <div class="btn-group">
                <button class="btn" onclick="subscribeTopic()">订阅</button>
                <button class="btn secondary" onclick="unsubscribeAll()">取消全部</button>
            </div>
            <div id="subscriptions"></div>
        </div>



        <!-- 消息发送 -->
        <div class="section">
            <h3>发送消息</h3>
            <div class="input-group">
                <label>消息类型:</label>
                <select id="messageType">
                    <option value="text">文本</option>
                    <option value="image">图片</option>
                    <option value="video">视频</option>
                    <option value="webpage">网页</option>
                    <option value="clear">清除</option>
                </select>
            </div>
            <div class="input-group">
                <label>内容/URL:</label>
                <input type="text" id="messageContent" placeholder="输入内容或URL">
            </div>
            <div class="input-group">
                <label>显示时长 (毫秒):</label>
                <input type="number" id="duration" placeholder="0表示一直显示" value="0">
            </div>
            <button class="btn" onclick="sendMessage()">发送</button>
        </div>

        <!-- 预设消息 -->
        <div class="section">
            <h3>预设消息</h3>
            <div class="preset-grid">
                <button class="preset-btn" onclick="sendPreset('welcome')">欢迎信息</button>
                <button class="preset-btn" onclick="sendPreset('image')">测试图片</button>
                <button class="preset-btn" onclick="sendPreset('video')">测试视频</button>
                <button class="preset-btn" onclick="sendPreset('webpage')">测试网页</button>
                <button class="preset-btn" onclick="sendPreset('clear')">清除显示</button>
                <button class="preset-btn" onclick="sendPreset('custom')">自定义</button>
            </div>
        </div>

        <!-- 日志 -->
        <div class="section">
            <h3>日志</h3>
            <div id="log" class="log"></div>
        </div>
    </div>

    <script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
    <script src="js/config.js"></script>
    <script>
        let mqttClient = null;
        let isConnected = false;
        let deviceId = null;
        let targetTopic = CONFIG.mqtt.baseTopic;
        let subscribedTopics = new Set();

        // 初始化
        function init() {
            // 使用config.js中的设备配置
            deviceId = CONFIG.device.id;
            
            if (deviceId) {
                document.getElementById('deviceId').value = deviceId;
                updateTargetTopic();
            }
            
            addLog('页面已加载，准备连接MQTT...');
            addLog('MQTT服务器: ' + CONFIG.mqtt.host + ':' + CONFIG.mqtt.port);
        }

        // 更新目标主题
        function updateTargetTopic() {
            const baseTopic = document.getElementById('targetTopic').value.trim() || CONFIG.mqtt.baseTopic;
            const deviceIdInput = document.getElementById('deviceId').value.trim();
            
            if (deviceIdInput) {
                targetTopic = `${baseTopic}/${deviceIdInput}`;
            } else {
                targetTopic = baseTopic;
            }
            
            addLog(`目标主题已更新: ${targetTopic}`);
        }

        // 连接MQTT
        function connectMQTT() {
            if (isConnected) return;
            
            const mqttUrl = `wss://${CONFIG.mqtt.host}:${CONFIG.mqtt.port}${CONFIG.mqtt.path}`;
            const clientId = CONFIG.mqtt.clientId.replace('display_client_', 'mobile_control_');
            
            mqttClient = mqtt.connect(mqttUrl, {
                clientId: clientId,
                username: CONFIG.mqtt.username,
                password: CONFIG.mqtt.password,
                reconnectPeriod: CONFIG.mqtt.reconnectPeriod,
                connectTimeout: CONFIG.mqtt.connectTimeout
            });

            mqttClient.on('connect', () => {
                isConnected = true;
                updateConnectionStatus(true);
                addLog('MQTT连接成功');
                addLog('目标主题: ' + targetTopic);
                
                // 重新订阅之前的主题
                subscribedTopics.forEach(topic => {
                    subscribeToTopic(topic);
                });
            });

            mqttClient.on('message', (topic, message) => {
                addLog(`📨 [${topic}]: ${message.toString()}`);
            });

            mqttClient.on('error', (err) => {
                addLog('❌ 错误: ' + err.message);
            });

            mqttClient.on('close', () => {
                isConnected = false;
                updateConnectionStatus(false);
                addLog('🔌 连接已断开');
            });
        }

        // 断开连接
        function disconnectMQTT() {
            if (mqttClient) {
                mqttClient.end();
                mqttClient = null;
            }
            isConnected = false;
            updateConnectionStatus(false);
        }

        // 更新连接状态显示
        function updateConnectionStatus(connected) {
            const status = document.getElementById('status');
            const statusDot = status.querySelector('.connection-status');
            
            if (connected) {
                status.innerHTML = '<span class="connection-status connected"></span>已连接';
            } else {
                status.innerHTML = '<span class="connection-status disconnected"></span>未连接';
            }
        }

        // 订阅主题
        function subscribeTopic() {
            const topic = document.getElementById('subscribeTopic').value.trim();
            if (!topic) {
                addLog('请输入要订阅的主题');
                return;
            }
            
            if (!isConnected) {
                addLog('请先连接MQTT');
                return;
            }
            
            if (subscribedTopics.has(topic)) {
                addLog('已经订阅了该主题: ' + topic);
                return;
            }
            
            subscribeToTopic(topic);
        }

        // 执行订阅
        function subscribeToTopic(topic) {
            mqttClient.subscribe(topic, (err) => {
                if (err) {
                    addLog('❌ 订阅失败: ' + err.message);
                } else {
                    subscribedTopics.add(topic);
                    addLog('✅ 订阅成功: ' + topic);
                    updateSubscriptionsDisplay();
                }
            });
        }

        // 取消订阅
        function unsubscribeTopic(topic) {
            if (!isConnected) {
                addLog('请先连接MQTT');
                return;
            }
            
            mqttClient.unsubscribe(topic, (err) => {
                if (err) {
                    addLog('❌ 取消订阅失败: ' + err.message);
                } else {
                    subscribedTopics.delete(topic);
                    addLog('🔕 取消订阅: ' + topic);
                    updateSubscriptionsDisplay();
                }
            });
        }

        // 取消所有订阅
        function unsubscribeAll() {
            if (!isConnected) {
                addLog('请先连接MQTT');
                return;
            }
            
            subscribedTopics.forEach(topic => {
                mqttClient.unsubscribe(topic, (err) => {
                    if (err) {
                        addLog('❌ 取消订阅失败: ' + err.message);
                    } else {
                        addLog('🔕 取消订阅: ' + topic);
                    }
                });
            });
            
            subscribedTopics.clear();
            updateSubscriptionsDisplay();
        }

        // 更新订阅显示
        function updateSubscriptionsDisplay() {
            const container = document.getElementById('subscriptions');
            container.innerHTML = '';
            
            subscribedTopics.forEach(topic => {
                const div = document.createElement('div');
                div.className = 'subscription-item';
                div.innerHTML = `
                    <span>${topic}</span>
                    <button onclick="unsubscribeTopic('${topic}')">取消</button>
                `;
                container.appendChild(div);
            });
        }

        // 发送消息
        function sendMessage() {
            if (!isConnected) {
                addLog('请先连接MQTT');
                return;
            }

            const type = document.getElementById('messageType').value;
            const content = document.getElementById('messageContent').value;
            const duration = parseInt(document.getElementById('duration').value) || 0;

            const message = { type };
            
            if (type === CONFIG.messageTypes.TEXT) {
                message.content = content;
            } else if (type !== CONFIG.messageTypes.CLEAR) {
                message.url = content;
            }
            
            if (duration > 0) message.duration = duration;
            if (type === CONFIG.messageTypes.VIDEO) {
                message.autoplay = true;
                message.muted = true;
            }

            publishMessage(message);
        }



        // 发送预设消息
        function sendPreset(type) {
            const presets = {
                welcome: { type: CONFIG.messageTypes.TEXT, content: '欢迎使用远程控制显示系统！', duration: 0 },
                image: { type: CONFIG.messageTypes.IMAGE, url: 'https://picsum.photos/1920/1080', duration: 0 },
                video: { type: CONFIG.messageTypes.VIDEO, url: 'https://sample-videos.com/video321/mp4/720/big_buck_bunny_720p_1mb.mp4', autoplay: true, muted: true, duration: 0 },
                webpage: { type: CONFIG.messageTypes.WEBPAGE, url: 'https://www.baidu.com', duration: 0 },
                clear: { type: CONFIG.messageTypes.CLEAR },
                custom: { type: CONFIG.messageTypes.TEXT, content: '这是自定义消息', duration: 0 }
            };

            if (presets[type]) {
                publishMessage(presets[type]);
            }
        }

        // 发布消息
        function publishMessage(message) {
            mqttClient.publish(targetTopic, JSON.stringify(message), (err) => {
                if (err) {
                    addLog('❌ ' + CONFIG.errors.mqttConnectionFailed + ': ' + err.message);
                } else {
                    addLog('📤 发送到 ' + targetTopic + ': ' + JSON.stringify(message));
                }
            });
        }

        // 添加日志
        function addLog(message) {
            const log = document.getElementById('log');
            const time = new Date().toLocaleTimeString();
            log.innerHTML += `<div>[${time}] ${message}</div>`;
            log.scrollTop = log.scrollHeight;
        }

        // 页面加载时初始化
        init();
    </script>
</body>
</html> 